package com.zmxstudy.gzu.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zmxstudy.gzu.domain.TbSpec;

import com.zmxstudy.gzu.mapper.TbSpecMapper;
import com.zmxstudy.gzu.mapper.TbTemplateMapper;
import com.zmxstudy.gzu.utils.ProductCodeMsg;
import com.zmxstudy.gzu.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "规格管理")
@RestController
@RequestMapping("/product-service/specs")
@SuppressWarnings("rawtypes")
public class SpecController {

    @Resource
    TbSpecMapper tbSpecMapper;
    @Resource
    TbTemplateMapper tbTemplateMapper;

    @Operation(summary = "根据TemplateId查询所有")
    @GetMapping("/{id}")
    Result<List<TbSpec>> findByTemplateId(@PathVariable Long id){
        LambdaQueryWrapper<TbSpec> laq=new LambdaQueryWrapper<>();
        laq.eq(TbSpec::getTemplateId,id);
        List<TbSpec> list = tbSpecMapper.selectList(laq);
        return Result.success("查询成功",list);
    }


    @Operation(summary = "查询所有")
    @GetMapping()
    Result<List<TbSpec>> findTbSpec(){
        List<TbSpec> list = tbSpecMapper.selectList(null);
        return Result.success("查询成功",list);
    }

    @Operation(summary = "添加规格")
    @PostMapping()
    public Result addSpec(@RequestBody TbSpec tbSpec){
        if (tbSpec.getName()==null || tbSpec.getOptions()==null){
            return Result.error(ProductCodeMsg.ADDSpec_error);
        }

        LambdaQueryWrapper<TbSpec> laq=new LambdaQueryWrapper<>();
        laq.eq(TbSpec::getTemplateId,tbSpec.getTemplateId());
        List<TbSpec> list = tbSpecMapper.selectList(laq);

        int judge = 0;
        for (TbSpec ts:list) {
            if (tbSpec.getName().equals(ts.getName())){
                judge = judge + 1;
            }
        }
        if (judge != 0){
            return Result.error(ProductCodeMsg.ADDSpec_error2);
        }

        tbSpecMapper.insert(tbSpec);
        return Result.success();
    }


    @Operation(summary = "修改规格")
    @PutMapping
    public Result updateSpec(@RequestBody TbSpec tbSpec){
        if (tbSpec.getName()==null || tbSpec.getOptions()==null){
            return Result.error(ProductCodeMsg.ADDSpec_error);
        }

        tbSpecMapper.updateById(tbSpec);
        return Result.success();
    }

    @Operation(summary = "删除规格")
    @DeleteMapping("/{id}")
    public Result deleteSpec(@PathVariable Long id){

        tbSpecMapper.deleteById(id);
        return Result.success();
    }
}
